<template>
  <!-- 新增/编辑弹窗 -->
  <el-dialog
    v-model="dialogVisible"
    :title="dialogTitle"
    width="60%"
    @close="handleClose"
    :destroy-on-close="true"
  >
    <el-form
      ref="dialogFormRef"
      :model="dialogForm"
      :rules="dialogRules"
      label-width="140px"
    >
      <el-row :gutter="24">
        <!-- 动态渲染所有字段 -->
        <template v-for="item in formSchema" :key="item.field">
          <!-- 输入框 -->
          <el-col :span="8" v-if="item.type === 'input'">
            <el-form-item :label="item.label" :prop="item.field">
              <el-input
                v-model="dialogForm[item.field]"
                :placeholder="item.placeholder || `请输入${item.label}`"
                :clearable="true"
              />
            </el-form-item>
          </el-col>

          <!-- 数字输入框 -->
          <el-col :span="8" v-else-if="item.type === 'number'">
            <el-form-item :label="item.label" :prop="item.field">
              <el-input-number
                v-model="dialogForm[item.field]"
                :min="item.min ?? null"
                :max="item.max ?? null"
                :placeholder="item.placeholder"
                style="width: 100%"
                :controls="false"
              />
            </el-form-item>
          </el-col>

          <!-- 下拉框 -->
          <el-col :span="8" v-else-if="item.type === 'select'">
            <el-form-item :label="item.label" :prop="item.field">
              <el-select
                v-model="dialogForm[item.field]"
                :placeholder="`请选择${item.label}`"
                style="width: 100%"
                :clearable="true"
              >
                <el-option
                  v-for="opt in item.options"
                  :key="opt.value"
                  :value="opt.value"
                  :label="opt.label"
                />
              </el-select>
            </el-form-item>
          </el-col>

          <!-- 单选框 -->
          <el-col :span="8" v-else-if="item.type === 'radio'">
            <el-form-item :label="item.label" :prop="item.field">
              <el-radio-group v-model="dialogForm[item.field]">
                <el-radio
                  v-for="opt in item.options"
                  :key="opt.value"
                  :label="opt.value"
                >
                  {{ opt.label }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </template>
      </el-row>
    </el-form>

    <!-- 按钮 -->
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">保 存</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, nextTick } from "vue";

// 弹窗控制
const dialogVisible = ref(false);
const dialogTitle = ref("新增字段配置");
const dialogFormRef = ref();

// 表单数据（动态）
const dialogForm = ref<Record<string, any>>({});

// ==================== 动态表单 Schema ====================
const formSchema = [
  { field: "title", label: "显示名称", type: "input", required: true },
  { field: "field", label: "字段英文名称", type: "input", required: true },
  { field: "width", label: "表格宽度", type: "number", min: 50, max: 1000 },
  { field: "sort", label: "排序", type: "number", min: 0, max: 999 },

  {
    field: "fieldType",
    label: "字段类型",
    type: "select",
    options: [
      { value: "varchar", label: "字符串" },
      { value: "int", label: "整数" },
      { value: "double", label: "小数" },
      { value: "datetime", label: "日期时间" },
      { value: "text", label: "文本" },
      { value: "boolean", label: "布尔值" },
    ],
  },
  {
    field: "formType",
    label: "表单类型",
    type: "select",
    options: [
      { value: "input", label: "输入框" },
      { value: "select", label: "下拉框" },
      { value: "date", label: "日期" },
      { value: "datetime", label: "日期时间" },
      { value: "textarea", label: "文本域" },
      { value: "switch", label: "开关" },
      { value: "upload", label: "上传" },
      { value: "radio", label: "单选框" },
    ],
  },
  {
    field: "fieldLength",
    label: "数据表字段长度",
    type: "number",
    min: 1,
    max: 1000,
  },
  { field: "dictType", label: "字典类型", type: "input" },
  { field: "tableAlias", label: "关联表别名", type: "input" },
  { field: "tableField", label: "关联表字段", type: "input" },
  { field: "selClassName", label: "选择类名称", type: "input" },
  { field: "selField", label: "选择类字段", type: "input" },
  {
    field: "searchCondition",
    label: "查询条件",
    type: "select",
    options: [
      { value: "eq", label: "等于" },
      { value: "ne", label: "不等于" },
      { value: "like", label: "模糊匹配" },
      { value: "gt", label: "大于" },
      { value: "ge", label: "大于等于" },
      { value: "lt", label: "小于" },
      { value: "le", label: "小于等于" },
    ],
  },
  {
    field: "searchValue",
    label: "查询值",
    type: "input",
    placeholder: "默认查询值",
  },

  // --- 布尔类字段：使用 radio ---
  {
    field: "isTable",
    label: "是否表格显示",
    type: "radio",
    required: true,
    options: [
      { value: "0", label: "否" },
      { value: "1", label: "是" },
    ],
  },
  {
    field: "isForm",
    label: "是否表单显示",
    type: "radio",
    required: true,
    options: [
      { value: "0", label: "否" },
      { value: "1", label: "是" },
    ],
  },
  {
    field: "isSearch",
    label: "是否查询",
    type: "radio",
    required: true,
    options: [
      { value: "0", label: "否" },
      { value: "1", label: "是" },
    ],
  },
  {
    field: "formRequire",
    label: "表单是否必填",
    type: "radio",
    required: true,
    options: [
      { value: "0", label: "否" },
      { value: "1", label: "是" },
    ],
  },
  {
    field: "exportExcel",
    label: "是否导出",
    type: "radio",
    required: true,
    options: [
      { value: "0", label: "否" },
      { value: "1", label: "是" },
    ],
  },
  {
    field: "importExcel",
    label: "是否导入",
    type: "radio",
    required: true,
    options: [
      { value: "0", label: "否" },
      { value: "1", label: "是" },
    ],
  },
  {
    field: "isSort",
    label: "是否排序",
    type: "radio",
    required: true,
    options: [
      { value: "0", label: "否" },
      { value: "1", label: "是" },
    ],
  },
  {
    field: "isTableEdit",
    label: "是否表格编辑",
    type: "radio",
    required: true,
    options: [
      { value: "0", label: "否" },
      { value: "1", label: "是" },
    ],
  },
  {
    field: "isFormEdit",
    label: "是否表单编辑",
    type: "radio",
    required: true,
    options: [
      { value: "0", label: "否" },
      { value: "1", label: "是" },
    ],
  },
  {
    field: "isTotal",
    label: "是否合计",
    type: "radio",
    required: true,
    options: [
      { value: "0", label: "否" },
      { value: "1", label: "是" },
    ],
  },
  {
    field: "isUnique",
    label: "是否唯一",
    type: "radio",
    required: true,
    options: [
      { value: "0", label: "否" },
      { value: "1", label: "是" },
    ],
  },

 
];

// 初始化表单数据
const initDialogForm = () => {
  const form: Record<string, any> = { id: null }
  formSchema.forEach(item => {
    if (['radio', 'select'].includes(item.type)) {
      form[item.field] = item.options?.[0]?.value ?? ''
    } else if (item.type === 'number') {
      form[item.field] = null
    } else {
      form[item.field] = ''
    }
  })
  return form
}

// 动态生成校验规则
const dialogRules = ref<Record<string, any[]>>(() => {
  const rules: Record<string, any[]> = {};
  formSchema.forEach((item) => {
    if (item.required) {
      rules[item.field] = [
        { required: true, message: `请选择${item.label}`, trigger: "change" },
      ];
    }
  });
  return rules;
});

// ==================== 操作方法 ====================

// 打开新增弹窗
const handleAddRow = () => {
  dialogTitle.value = "新增字段配置";
  Object.assign(dialogForm.value, initDialogForm());
  dialogVisible.value = true;
  nextTick(() => {
    dialogFormRef.value?.clearValidate();
  });
};

// 打开编辑弹窗
const handleEdit = (row: Record<string, any>) => {
  if (!row) {
    ElMessage.error('无法编辑：数据为空')
    return
  }

  dialogTitle.value = '编辑字段配置'
  Object.assign(dialogForm.value, initDialogForm())

  // 直接从 row 赋值到 dialogForm
  formSchema.forEach(item => {
    const val = row[item.field]
    if (val !== undefined && val !== null) {
      dialogForm.value[item.field] = val
    }
  })

  dialogVisible.value = true
  nextTick(() => {
    dialogFormRef.value?.clearValidate()
  })
}

// 关闭弹窗
const handleClose = () => {
  dialogFormRef.value?.resetFields();
};

// 提交表单
const submitForm = () => {
  dialogFormRef.value?.validate((valid: boolean) => {
    if (!valid) return;

    const data = { ...dialogForm.value };

    // 生成临时 ID（实际应由后端生成）
    // if (!data.id) {
    //   data.id = "temp_" + Date.now();
    // }

    // 触发保存（由父组件处理）
    emit("save", data);

    dialogVisible.value = false;
  });
};

// ==================== 事件 ====================
// 定义 emits
const emit = defineEmits(["save"]);

// 暴露方法给父组件
defineExpose({
  handleAddRow,
  handleEdit,
});
</script>

<style scoped lang="scss">
.dialog-footer {
  text-align: right;
  padding-top: 10px;
}
.dialog-footer .el-button:first-child {
  margin-right: 10px;
}
</style>
